package mysql

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"jd-mall/config"
	"log"
	"time"
)

var (
	err error
	DB  *gorm.DB
)

func Init() {
	mData := config.ConfigData.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True", mData.Username, mData.Password, mData.Host, mData.Port, mData.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("Mysql数据库连接失败")
	} else {
		log.Println("Mysql数据库连接成功")
	}

	var sqlDB *sql.DB
	sqlDB, err = DB.DB()
	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)

	err = DB.AutoMigrate(&Shops{}, &ShopImage{})
	if err != nil {
		panic("Mysql数据表迁移失败")
	} else {
		log.Println("Mysql数据表迁移成功")
	}
}
